package com.code.bolg.service.impl;

import com.code.bolg.bean.Comment;
import com.code.bolg.enums.ResultEnum;
import com.code.bolg.exception.BolgExcetion;
import com.code.bolg.repository.CommentRepository;
import com.code.bolg.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Override
    public Comment save(Comment comment) {
        Comment save = commentRepository.save(comment);
        return save;
    }

    @Override
    public int deleteById(int id) {

        Optional<Comment> optional=commentRepository.findById(id);
        if(optional.isPresent()){
            commentRepository.deleteById(id);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public Comment findById(int id) {
        Optional<Comment> optional = commentRepository.findById(id);
        if (optional.isPresent()) {
            Comment comment = optional.get();
            return comment;
        } else {
            throw new BolgExcetion(ResultEnum.NOTFINDDATA);
        }
    }

    @Override
    public List<Comment> findAll(Comment comment,int pageNumber,int pageSize) {
        //分页构造
        Pageable pageable = PageRequest.of(pageNumber,pageSize);
        Page<Comment> all = commentRepository.findAll( pageable);
        return  all.getContent();
    }
}
